package com.ch.mafia.process;

import java.util.List;

import org.json.JSONObject;

import com.ch.mafia.base.BaseProcess;
import com.ch.mafia.bean.SPlayerBean;

public class PlayerProcess extends BaseProcess{

	public List<JSONObject> getHousePlayer(String houseId) throws Exception{
		return baseDao.queryList("s_house as a,s_player as b,s_user as c",new String[]{"c.id as userid","c.point","c.nickname","c.playnum",
					"c.winnum","b.id as playerid","b.seat","b.role","b.dead"},
							"a.id=b.houseid and b.userid = c.id and a.id="+houseId,null, null, null);
	}
	
	public void addPlayer(String houseId,String userId) throws Exception{
		SPlayerBean sPlayerBean =new SPlayerBean();
		sPlayerBean.setHouseid(Integer.parseInt(houseId));
		sPlayerBean.setRole(0);
		sPlayerBean.setSeat(getSeat(houseId));
		sPlayerBean.setUserid(Integer.parseInt(userId));
		baseDao.add(sPlayerBean.getJsonObject());
	}
	
	public int getSeat(String houseId) throws Exception{
		int result =0;
		List<JSONObject> jsonObjects = getHousePlayer(houseId);
		int[] seats =new int[new HouseInfoProcess().getHouseMaxNum(houseId)];
		for(int j=0;j<seats.length;j++){
			boolean hasPlayer =false;
			for(int i = 0;i<jsonObjects.size();i++){
					if(jsonObjects.get(i).getInt("seat")==seats[j]){
						hasPlayer = true;
						break;
					}
			}
			if(!hasPlayer){
				result =seats[j];
				return result;
			}
		}
		return result;
	}
	
	public void deletePlayer(String userId) throws Exception{
		baseDao.delete("s_player", "userid="+userId);
	}
	
}
